package com.qf.day07.user;

import java.util.Arrays;

public class UserServiseImpl implements UserService{
    //创建一个用户数组来存放用户信息
    private User[] userArr = new User[5];
    //创建一个属性记录注册了多少用户,同时属性值即为数组下标
    private int count=0;

    public UserServiseImpl() {
    }

    public UserServiseImpl(User[] userArr) {
        this.userArr = userArr;
    }

    public User[] getUserArr() {
        return userArr;
    }

    public void setUserArr(User[] userArr) {
        this.userArr = userArr;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    @Override
    public boolean register(String nameRegis, String password) {
        //检查用户是否存在
        boolean flag= checkName(nameRegis);
        if(flag){
            return false;
        }
        //创建一个user对象,将user对象保存起来
        User user1 = new User(nameRegis, password);
        userArr[count++]=user1;
        //判断用户数组是否需要扩容
        if(count== userArr.length){
            userArr=Arrays.copyOf(userArr,userArr.length*2);
        }
        return true;
    }

    private boolean checkName(String nameRegis) {
        for (int i = 0; i < count; i++) {
            if (userArr[i].getUsername().equals(nameRegis)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean login(String nameLogin, String password) {
        for (int i = 0; i < count; i++) {
            if(userArr[i].getUsername().equals(nameLogin)&&userArr[i].getPassword().equals(password)){
                return true;
            }
        }
        return false;
    }
}
